<template>
  <view class="byt-message">
    <view v-if="createTime" class="byt-message__time">{{ createTime }}</view>
    <view
        class="byt-message__content is-wide"
        :class="{
        'is-auto': isAuto,
        'is-mine': !isAuto,
        'is-avatar': configAgent.avatar,
        'is-username': configAgent.name
      }"
    >
      <!-- 头像 -->
      <view v-if="configAgent.avatar" class="byt-message__content-avatar">
        <basic-icon size="62rpx" shape="circle" :name="configAgent.avatar"></basic-icon>
      </view>

      <!-- 气泡内容容器 - 添加相对定位 -->
      <view class="byt-message__content-box relative-position"
            :style="{ background: !isAuto ? (colorIcon.userBgColor ? colorIcon.userBgColor : '#448ef7') : '', opacity: 0.95 }"
            @longpress="showContextMenu($event)">

        <!-- 用户名称 -->
        <view v-if="configAgent.name" class="byt-message__content-box__username">
          {{ configAgent.name }}
        </view>

        <!-- 内容区域包装器 -->
        <view class="message-content-wrapper" style="position: relative;">
          <!-- 左边内容 -->
          <template v-if="isAuto">
            <!-- 发送 -->
            <view v-if="verifyPermission('send')" class="byt-message__content-box__text byt-message__content-box--default" style="padding-bottom: 14rpx">
              <zero-markdown-view :markdown="msgContent(content)"></zero-markdown-view>
              <text class="byt-message__content-box__text-btn" style="margin-left: 0" @click="onSend">去发送</text>
            </view>

            <!-- 非文件内容 -->
            <view v-else v-show="contentType!=='FILE'">
              <!-- 深度思考回答 -->
              <Think v-if="deepSeekContent" :status="deepSeekStatus" :time="deepSeekTime" :content="deepSeekContent"></Think>

              <!-- 文本或图文 -->
              <zero-markdown-view :markdown="msgContent(content)"></zero-markdown-view>
            </view>

            <!-- 图表 -->
            <Chart v-if="verifyPermission('chart')" :type="contentType" :dataObj="contentAppendData"></Chart>

            <!-- 表格 -->
            <Tables v-if="verifyPermission('tables')" :columns="JSON.parse(contentAppendData).tableColumns" :data="JSON.parse(contentAppendData).tableData"></Tables>

            <!-- 活动 -->
            <Activity v-if="verifyPermission('activity')" :items="JSON.parse(contentAppendData)"></Activity>

            <!-- 优惠券 -->
            <Coupon v-if="verifyPermission('coupon')" :items="JSON.parse(contentAppendData)"></Coupon>

            <!-- 商品 -->
            <Goods v-if="verifyPermission('goods')" :items="JSON.parse(contentAppendData)"></Goods>

            <!-- 文件 -->
            <File v-if="verifyPermission('FILE')" :file="contentAppendData"></File>

            <!-- 功能栏（保持在原位置） -->
            <view class="byt-message__content-box__response">
              <slot name="footer"></slot>
            </view>
          </template>

          <!-- 右边内容（用户消息） -->
          <template v-else>
            <view class="byt-message__content-box__text"
                  :style="{ color: colorIcon.userTextColor ? colorIcon.userTextColor : '#FFFFFF' }">
              <zero-markdown-view :markdown="msgContent(content)"></zero-markdown-view>
            </view>
          </template>

          <!-- 使用遮罩层组件 -->
          <MessageMask @longpress="showContextMenu" @touchmove="handleTouchMove" v-show="contentType!=='FILE'"/>
        </view>
      </view>
    </view>

    <!-- 长按弹窗 - 移至气泡容器外，使用fixed定位 -->
    <view
        v-if="contextMenuVisible"
        class="context-menu"
        :class="{
      'menu-enter': animationState === 'enter',
      'menu-visible': animationState === 'visible',
      'menu-left': isAuto,
      'menu-right': !isAuto
    }"
        :style="{
      top: menuTop + 'px',
      left: menuLeft + 'px'
    }"
        @click.stop
    >
      <view class="context-menu-item" @click="edit" v-show="!isAuto"
            @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchcancel="handleTouchEnd">
        <uv-icon name="edit-pen" size="14" color="rgb(0, 136, 238)"></uv-icon>
        <text>编辑</text>
      </view>
      <view class="context-menu-item" @click="copyMessage"
            @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchcancel="handleTouchEnd">
        <uv-icon name="order" size="14" color="rgb(0, 136, 238)"></uv-icon>
        <text>复制</text>
      </view>
      <view class="context-menu-item" @click="selectMessage"
            @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchcancel="handleTouchEnd">
        <uv-icon name="attach" size="14" color="rgb(0, 136, 238)"></uv-icon>
        <text>选取文本</text>
      </view>
      <view class="context-menu-item" @click="deleteMessage"
            @touchstart="handleTouchStart" @touchend="handleTouchEnd" @touchcancel="handleTouchEnd">
        <uv-icon name="trash" size="14" color="rgb(255, 0, 0)"></uv-icon>
        <text>删除</text>
      </view>
    </view>

    <!-- 遮罩层 - 保持在最外层 -->
    <view
        v-if="contextMenuVisible"
        class="context-menu-overlay"
        @click="closeContextMenu"
        @longpress="closeContextMenu"
        @touchmove="closeContextMenu"
    ></view>
  </view>
</template>

<script>
import Think from '../Think/Think.vue';
import { Group, isJsonString, getCurrentDateTime, showToast } from '../../../utils/index.js';
import zeroMarkdownView from './components/zero-markdown-view/components/zero-markdown-view/zero-markdown-view.vue';
import BasicIcon from '../../basic/basic-icon/basic-icon.vue';
import Activity from '../Activity/Activity.vue';
import Coupon from '../Coupon/Coupon.vue';
import Goods from '../Goods/Goods.vue';
import Chart from '../Chart/Chart.vue';
import Tables from '../Tables/Tables.vue';
import File from '../File/File.vue';
import Login from "@/pages/login/index.vue";
// 导入遮罩层组件
import MessageMask from '@/components/module/MessageMask.vue';

export default {
  name: 'Bubble',
  components: {
    BasicIcon,
    Activity,
    Coupon,
    Goods,
    Chart,
    Tables,
    File,
    zeroMarkdownView,
    Think,
    MessageMask
  },
  emits: ['response'],
  props: {
    // 主题色和图标
    colorIcon: {
      type: Object,
      default: () => {
        return {
          mainColor: '#448ef7',
          assistColor: '#a8ecff',
          textMainColor: '#1890ff',
          linearColor: '#00E1CA,#90F3D0',
          userTextColor: '#FFFFFF',
          userBgColor: '#448ef7'
        };
      }
    },
    placement: {
      type: String,
      default: 'start'
    },
    contentType: {
      type: String,
      default: 'text'
    },
    config: {
      type: Object,
      default: () => {
        return {
          name: 'AI助手',
          avatar: 'https://img.yummall.cn/baiyetong/byt-uni-ui/role_icon_1.svg',
          placement: 'start'
        };
      }
    },
    typeWhiteList: {
      type: Array,
      default: () => {
        return ['text', 'activity', 'coupon', 'goods', 'chart', 'tables', 'action', 'image', 'file', 'txt'];
      }
    },
    contentAppendData: {
      type: String || null,
      default: null
    },
    createTime: {
      type: String,
      default: ''
    },
    content: {
      type: String,
      default: ''
    },
    deepSeekContent: {
      type: String,
      default: ''
    },
    deepSeekStatus: {
      type: Boolean,
      default: false
    },
    deepSeekTime: {
      type: Number,
      default: 0
    },
    // 菜单位置配置
    menuPosition: {
      type: String,
      default: 'bottom', // 可选值：'top' 或 'bottom'
      validator: (value) => ['top', 'bottom'].includes(value)
    },
    senderHeight: {
      type: Number,
      default: 0
    },
    chatId: {
      type: String,
      default: ''
    },
    conversationId: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      contextMenuVisible: false,
      isMoved: false,
      animationState: '', // 动画状态
      menuTop: 0,         // 弹窗顶部位置
      menuLeft: 0,        // 弹窗左侧位置
      bubbleRect: null,    // 气泡的位置信息
      menuRight: 0,  // 添加menuRight属性
      useRight: false // 添加useRight标
    };
  },
  computed: {
    isAuto() {
      return this.placement === 'start';
    },
    configAgent() {
      return this.config || {};
    }
  },
  methods: {
    handleTouchStart(e, index) {
      // 防止冒泡到上层元素
      e.stopPropagation();

      // 设置当前按下的菜单项索引
      this.pressedItemIndex = index;
      this.isMenuItemPressed = true;

      // 自动在200ms后取消按下状态，防止长时间保持高亮
      clearTimeout(this.pressTimeout);
      this.pressTimeout = setTimeout(() => {
        this.isMenuItemPressed = false;
      }, 200);
    },

    handleTouchEnd() {
      // 清除按下状态
      this.isMenuItemPressed = false;
      this.pressedItemIndex = -1;
    },
    handleTouchMove() {
      this.isMoved = true;
      this.closeContextMenu();
    },
    lp() {
      showToast('长按了');
    },
    isJsonString,
    msgContent(content) {
      if (!content) return content;
      let htmlString = content;
      if (htmlString[htmlString.length - 1] !== '\n') {
        htmlString += '\n';
      }
      return htmlString;
    },
    verifyPermission(type) {
      let permission = this.typeWhiteList.includes(type);
      let tempContentType = this.contentType === type;
      if (type === 'chart') {
        tempContentType = this.contentType.startsWith('chart');
      }
      return tempContentType && permission;
    },
    previewImage(url) {
      uni.previewImage({
        current: 1,
        urls: [url],
        longPressActions: {
          itemList: ['保存图片'],
          success: (data) => {
            this.saveImage(url);
          },
          fail: (err) => {
            console.log(err.errMsg);
          }
        }
      });
    },
    saveImage(src) {
      uni.downloadFile({
        url: src,
        success: (res) => {
          if (res.statusCode === 200) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                uni.showToast({
                  title: '保存成功',
                  icon: 'success',
                  duration: 2000
                });
              },
              fail: (err) => {
                console.log('保存失败：', err);
              }
            });
          }
        },
        fail: (err) => {
          console.log('下载失败：', err);
        }
      });
    },
    onSend() {
      this.$emit('response', {type: 'send'});
    },

    showContextMenu(e) {
      if (this.verifyPermission('FILE')){
        return;
      }
      if (this.isMoved) {
        this.isMoved = false;
        return;
      }
      e.stopPropagation();

      // 获取手指按下的坐标
      const touch = e.touches[0];
      let menuTop = touch.clientY;
      let menuLeft = touch.clientX;

      // 获取系统信息
      const windowHeight = uni.getSystemInfoSync().windowHeight;
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const menuHeight = 200; // 弹窗高度(rpx)
      const menuWidth = 160;  // 弹窗宽度(rpx)

      // 检查并调整垂直位置
      if (menuTop + menuHeight +this.senderHeight > windowHeight) {
        menuTop = windowHeight - menuHeight-this.senderHeight;
      }
      if (menuTop < 0) {
        menuTop = 0;
      }

      // 检查并调整水平位置
      if (menuLeft + menuWidth > windowWidth) {
        menuLeft = windowWidth - menuWidth;
      }
      if (menuLeft < 0) {
        menuLeft = 0;
      }

      // 更新菜单位置
      this.menuTop = menuTop;
      this.menuLeft = menuLeft;

      // 显示菜单并添加动画
      this.contextMenuVisible = true;
      this.animationState = 'enter';

      setTimeout(() => {
        this.animationState = 'visible';
      }, 10);
    },

    // 关闭长按弹窗
    closeContextMenu() {
      this.animationState = 'exit';
      setTimeout(() => {
        this.contextMenuVisible = false;
        this.animationState = '';
      }, 200);
    },

    // 复制消息
    copyMessage() {
      uni.setClipboardData({
        data: this.content,
        success: () => {
          showToast('复制成功');
          this.closeContextMenu();
        },
        fail: () => {
          showToast('复制失败', 'error');
        }
      });
    },
    deleteMessage() {
      this.closeContextMenu();
      let params = {
        chatId:this.chatId,
        conversationId:this.conversationId
      }
      uni.$emit('deleteMessage',params)
    },
    selectMessage() {
      uni.$emit('selectText',this.content)
      this.closeContextMenu();
    },

    edit() {
      uni.$emit('edit',this.content)
      this.closeContextMenu();
    }
  }
};
</script>

<style lang="scss" scoped>
@include b(message) {
  @include e(time) {
    text-align: center;
    margin: 24rpx 0;
    font-size: 24rpx;
    color: #949099;
  }

  @include e(content) {
    display: flex;
    padding: 0 24rpx;
    margin: 32rpx 0;
    $selector: &;

    @include eb(box) {
      position: relative; // 添加相对定位
      padding: 8rpx 24rpx;
      border-radius: 0 24rpx 24rpx 24rpx;
      background: rgba(255, 255, 255, 0.9);
      max-width: 740rpx;
      box-sizing: border-box;
      z-index: 1; // 确保气泡容器层级低于弹窗

      @include e(text) {
        white-space: break-spaces;
        word-break: break-all;
        line-height: 48rpx;
        font-size: 28rpx;
        min-width: 0;

        @include eb(btn) {
          font-size: 14px;
          color: #8848cb;
          margin-left: 10px;
        }
      }

      @include e(btn) {
        padding: 16rpx 26rpx;
        border-radius: 60rpx;
        background: #3378ff14;
        color: #3378ffff;
        flex-shrink: 0;
      }

      @include e(response) {
        padding: 10rpx 16rpx;
        border-radius: 4px;
        left: 0rpx;
        bottom: -50rpx;
        position: absolute;
        display: flex;
        align-items: center;
        width: 100%;
        z-index: 20;
      }

      @include m(default) {
        color: #333333;
      }

      @include e(username) {
        display: none;
        position: absolute;
        top: -44rpx;
        color: #666666;
        font-size: 28rpx;
        white-space: nowrap;
      }
    }

    @include eb(avatar) {
      display: none;
      width: 62rpx;
      height: 62rpx;
      position: relative;
      top: -10rpx;
    }

    &.is-avatar {
      #{$selector + '-box'} {
        max-width: 610rpx;
      }

      #{$selector + '-avatar'} {
        display: block;
      }
    }

    &.is-username {
      #{$selector + '-box'} {
        margin-top: 40rpx;

        @include e(username) {
          display: block;
          white-space: nowrap;
          max-width: 200rpx;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }

    &.is-auto {
      flex-direction: row;

      #{$selector + '-box'} {
        margin-bottom: 60rpx;

        @include e(username) {
          left: 0;
        }

        @include e(text) {
          min-width: 60rpx;
        }
      }

      #{$selector + '-avatar'} {
        margin-right: 16rpx;
      }
    }

    &.is-mine {
      flex-direction: row-reverse;

      #{$selector + '-box'} {
        margin-left: 16rpx;
        position: relative;
        border-radius: 24rpx 0 24rpx 24rpx;
        background: rgba(26, 160, 255, 0.9);
        color: white;

        @include e(text) {
          color: white;
        }

        @include e(username) {
          right: 0;
          text-align: right;
        }
      }

      #{$selector + '-avatar'} {
        margin-left: 16rpx;
      }
    }

    &.is-wide {
      #{$selector + '-box'} {
        max-width: calc(100% - 40px);
      }
    }
  }
}

/* 长按弹窗样式 */
.context-menu {
  position: fixed;  // 使用fixed定位脱离文档流
  z-index: 9999;    // 确保弹窗层级最高
  width: 280rpx;
  background-color: white;
  border-radius: 12rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
  overflow: hidden;
  opacity: 0;
  transform: scale(0.95);
  transition: opacity 0.2s ease, transform 0.2s ease;
  white-space: nowrap;

  &.menu-enter {
    opacity: 0;
    transform: scale(0.95);
  }

  &.menu-visible {
    opacity: 1;
    transform: scale(1);
  }

  /* 左侧消息气泡的菜单 */
  &.menu-left {
    transform-origin: top left;
  }

  /* 右侧消息气泡的菜单 */
  &.menu-right {
    transform-origin: top right;
  }
}

.context-menu-item {
  display: flex;
  align-items: center;
  padding: 20rpx 24rpx;
  font-size: 28rpx;
  color: #333;
  transition: background-color 0.2s;

  // 添加点击高亮效果
  &:active, &.active {
    background-color: rgba(68, 142, 247, 0.15); // 使用主题色的半透明背景
  }
}

.context-menu-item text {
  margin-left: 12rpx;
}

.context-menu-item:nth-child(1) {
  border-bottom: 1rpx solid #f1f1f1;
}

.context-menu-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0);  // 完全透明背景
  z-index: 9998;  // 遮罩层级低于弹窗但高于其他内容
}
</style>